<?php

namespace app\common\model;

use app\common\model\BaseModel;
use think\Exception;


class CityAgent extends BaseModel
{

    // 表名
    protected $name = 'city_agent';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text',
        'create_time_text',
        'update_time_text'
    ];
    

    
    public function getStatusList()
    {
        return ['reviewing' => __('Reviewing'), 'normal' => __('Normal'), 'refused' => __('Refused'), 'trash' => __('Trash')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['update_time']) ? $data['update_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public static function onBeforeUpdate($data)
    {

        if ($data['status']=='normal') {
            $check_exist=self::where([['id','<>',$data['id']],['city','=',$data['city']],['status','=','normal']])->find();
            if($check_exist){
                throw new Exception('此城市已有另一个城市代理人。');
            }
        }
    }

    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id')->joinType('LEFT');
    }
    public function city()
    {
        return $this->belongsTo('Area', 'city', 'id')->joinType('LEFT');
    }
}
